<template>
  <div id="kcDetail" class="sceneDetail">
    <div style="margin-bottom: 20px;" class="sceneStep">
      <template>
        <Steps :current="currentIndex" direction="vertical" class="step-group">
          <Step
            title="赛前设置"
            @click.native="exchangeStatus('preCompeManage', 0)"
            :class="{ curStep: contestStatus != 2 }"
            :icon="contestStatus != 2 ? 'ios-refresh-circle' : ''"
            content="提供赛前题目、竞赛选手的管理"
          ></Step>
          <Step
            title="赛后归档"
            @click.native="exchangeStatus('endCompeManage', 1)"
            :class="{ curStep: contestStatus == 2 }"
            :icon="contestStatus == 2 ? 'ios-refresh-circle' : ''"
            content="提供赛后竞赛选手成绩的管理和统计"
          ></Step>
        </Steps>
      </template>
      <div class="countdown" v-if="contestStatus != 2">
        <span v-if="contestStatus == 0">开始</span
        ><span v-if="contestStatus == 1">结束</span>倒计时：<b>
          <span>{{ time.h }}</span
          >:<span>{{ time.m }}</span
          >:<span>{{ time.s }}</span></b
        >
      </div>
      <div class="btn-group">
        <div class="flex">
          <Poptip
            confirm
            title="为确保可视化展示效果，建议使用chrome浏览器查看大屏。"
            @on-ok="showVisualization()"
            transfer
            word-wrap
            width="250"
          >
            <Button type="primary">
              <img src="../../../assets/scene/dis-screen.png" />可视化展示
            </Button>
          </Poptip>
          <!--<Dropdown>
            <Button type="primary">
              	可视化展示
              <Icon type="ios-arrow-down"></Icon>
            </Button>
            <DropdownMenu slot="list">
              <DropdownItem @click.native="showVisualization()">知识赛</DropdownItem>
            </DropdownMenu>
          </Dropdown>-->
          <!--<Button type="primary" @click="showKnowLedgeCompetModel" v-if="contestStatus == 2">
	          	<img src="../../../assets/scene/start-scene.png" alt=""/>重新开始比赛</Button>-->
          <Poptip
            confirm
            title="确定要开始比赛？"
            @on-ok="changeCompetitionStatus('start')"
            transfer
            word-wrap
          >
            <!--v-if="contestStatus != 2"-->
            <Button
              type="primary"
              :ghost="startContestStatus || !hasUser || !hasQues"
              :disabled="startContestStatus || !hasUser || !hasQues || notOwnCompetition"
            >
              <img
                src="../../../assets/scene/dis-start-scene.png"
                alt=""
                v-if="startContestStatus || !hasUser || !hasQues || notOwnCompetition"
              />
              <img src="../../../assets/scene/start-scene.png" alt="" v-else />开始比赛</Button
            >
          </Poptip>
          <Poptip
            confirm
            title="确定要结束比赛？"
            @on-ok="changeCompetitionStatus('end')"
            transfer
            word-wrap
          >
            <Button
              type="primary"
              :ghost="stopContestStatus"
              :disabled="stopContestStatus || notOwnCompetition"
            >
              <img
                src="../../../assets/scene/dis-stop-scene.png"
                alt=""
                v-if="stopContestStatus || notOwnCompetition"
              />
              <img src="../../../assets/scene/stop-scene.png" alt="" v-else />结束比赛</Button
            >
          </Poptip>
          <Button type="primary" v-if="currentStatus === 'endCompeManage'" @click="gotoReportPage">
            <img src="../../../assets/scene/btn-report.png" />报告</Button
          >
        </div>
        <div style="width:316px;">
          <span style="color:#ff9900;font-size:14px">
            <Icon type="ios-information-circle-outline" />
            开始比赛前请先配置竞赛选手和题目，如果已经配置完成，开始按钮不可点，请点击 </span
          ><a @click="validateStart" style="font-size: 14px;">校验</a>
        </div>
      </div>
    </div>
    <knowledge-pre-manage v-if="currentIndex === 0" ref="preCompet"></knowledge-pre-manage>
    <knowledge-end-manage
      v-if="currentIndex === 1"
      :contestStatus="contestStatus"
    ></knowledge-end-manage>
    <knowledge-model ref="knowledgeModels" @getList="getContestStatus(true)"></knowledge-model>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations } from 'vuex';
import knowledgeEndManage from './knowledgeEndManage';
import knowledgePreManage from './knowledgePreManage';
import knowledgeModel from './knowledgeModel';
import { changeCompetitionSta, getCompetitionDetail } from '@/api/competition';
import usally from '@/mixin/usally';
import encryption from '@/libs/encryption.js';
import { sendToSence } from '@/api/boardcast_new.js';
import { getSenceUserList } from '@/api/knowledgeCompet';
import timer from '@/mixin/timer';
import commonFun from '../mixin.js'; //一些公共方法(获取比赛人员和比赛题目等)，用来判断是否可以计算积分，开始比赛等等
export default {
  name: 'knowledgeDetail',
  components: {
    knowledgePreManage,
    knowledgeEndManage,
    knowledgeModel
  },
  mixins: [usally, timer, commonFun],
  data: function() {
    let September = sessionStorage.getItem('November');
    September = JSON.parse(encryption.SelfUseDecrypt(September));
    return {
      USER_ID: September.userId,
      isRootDesigner: September.isRootDesigner,
      contestName: '',
      prePage: parseInt(this.$route.query.page),
      startContestStatus: false,
      stopContestStatus: false,
      contestStatus: '0',
      // backObj: {
      //   path: '/KLGCompet',
      //   name: 'KLGCompet',
      //   component: resolve => {
      //     require(['@/components/drillDesign/knowledgeCompontion/mains.vue'], resolve);
      //   },
      //   query: {
      //     page: 0,
      //   }
      // },
      currentStatus: 'preCompeManage',
      currentIndex: this.$route.query.status == '2' ? 1 : 0
    };
  },
  computed: {
    ...mapGetters('compet', ['passParams']),
    ...mapState('compet', ['hasUser', 'hasQues']),
    notOwnCompetition() {
      return this.USER_ID !== this.passParams.createUserId;
    }
  },
  watch: {
    contestStatus(val, oldVal) {
      if (val != oldVal && oldVal) {
        this.getContestStatus(true);
      }
    },
    passParams(val) {
        if (val.name === this.passParams.name) {
            return;
        }
        this.$store.commit('addBreadItem', { name: val.name });
    }
  },
  methods: {
    // 覆盖timer.js中的getDrillDetail方法，用于在更新服务器时间时同步更新夺旗赛状态
    getDrillDetail() {
      this.getContestStatus();
    },
    gotoReportPage() {
      const { href } = this.$router.resolve({
        name: 'kcReport',
        query: {
          id: this.passParams.id,
          type: 3
        }
      });
      window.openTrain(href, '_blank');
    },
    exchangeStatus(val, i) {
      if (this.contestStatus === '0') {
        //this.$Message.info('比赛尚未开始，请稍后再查看比赛成绩！')
        return;
      } else {
        this.currentStatus = val;
        this.currentIndex = i;
      }
    },
    addBoardCast(val) {
      let content = '"' + this.passParams.name + '"竞赛 "' + val + '了"';
      let params = {
        broadid: '',
        content: content,
        drillitmeinstancetaskid: '',
        drillitmetaskname: '',
        sender: this.USER_ID,
        sendtime: '',
        teamid: '',
        title: content,
        type: 1
      };
      addBoardCast(params).then((data) => {
        if (data.code == 1) {
        }
      });
    },
    //    getCompetList(){
    //      let params = {
    //      	page:1,
    //      	rows:2
    //      }
    //      getSenceUserList(params).then(data=>{
    //        if(data.code==1){
    //          this.tableData = [];
    //          let users = data.attribute.dataList;
    //          users.forEach(user => {
    //            //获取每个用户的详细信息，从而获取登录状态
    //            getUserInfo(user.userId).then(data => {
    //              if (data.code == 1) {
    //                user.online = data.data.online;
    //                this.tableData.push(user);
    //              }
    //            });
    //          })
    //          this.total = data.attribute.totalCount
    //        }
    //      })
    //    },
    //    sendToUser(){
    //				let userType = 'experimenter';
    //				let params = {
    //					"content": this.formValidate.content,
    //					"id": "",
    //					"status": 0,
    //					"title": "",
    //					"type": 1,
    //					"users": [
    //					    {
    //					      "userIds": this.formValidate.userIds,
    ////							      "userType": userType
    //					    }
    //					]
    //				}
    //				sendToUser(params).then(data => {
    //					if(data.code==1){
    //						this.$Message.info('发送成功');
    //						this.getBoardCastList();
    //						this.$emit('hideModal');
    //					}else{
    //						this.$Message.error(data.message);
    //					}
    //				})
    //			},
    //修改竞赛状态
    changeCompetitionStatus(state) {
      let _this = this;
      let str = '测试开启';
      let sta = 'adwBeforeCom';
      let params = {};
      params.state = state;
      if (state.indexOf('end') >= 0) {
        str = '关闭';
        sta = 'adwComed';
        changeCompetitionSta(this.passParams.id, params).then((data) => {
          if (data.code == 1) {
            //已关闭--2
            _this.currentStatus = 'endCompeManage';
            _this.exchangeStatus('endCompeManage', 1);
            _this.startContestStatus = true;
            _this.stopContestStatus = true;
            _this.contestStatus = '2';
          } else {
            _this.$Message.warning(data.message);
          }
        });
      } else if (state.indexOf('start') >= 0) {
        str = '开启';
        sta = 'adwComing';
        changeCompetitionSta(this.passParams.id, params).then((data) => {
          if (data.code == 1) {
            //进行中---1
            _this.startContestStatus = true;
            _this.stopContestStatus = false;
            _this.contestStatus = '1';
          } else {
            _this.$Message.warning(data.message);
          }
        });
      }
    },
    //获取竞赛状态
    getContestStatus(needServerTime) {
      let _this = this;
      let params = {};
      params.page = 1;
      params.rows = 100000;
      params.matchMode = '3';
      if (this.passParams.createUserId != this.USER_ID && !this.isRootDesigner) {
        _this.startContestStatus = true;
        _this.stopContestStatus = true;
        getCompetitionDetail(this.passParams.id).then((data) => {
          if (data.code == 1) {
            let contest = data.attribute.data;
            _this.contestStatus = contest.activityStatus;
            _this.competeDetail = contest;
            if (_this.contestStatus == '1') {
              _this.currentStatus = 'preCompeManage';
              if (needServerTime) {
                if (this.timeout) {
                  clearTimeout(this.timeout);
                }
                this.getServeTime(new Date(contest.endDate).getTime());
              }
            } else if (_this.contestStatus == '0') {
              _this.currentStatus = 'preCompeManage';
              if (needServerTime) {
                if (this.timeout) {
                  clearTimeout(this.timeout);
                }
                this.getServeTime(new Date(contest.startDate).getTime());
              }
            } else {
              _this.currentStatus = 'endCompeManage';
              if (needServerTime) {
                if (this.timeout) {
                  clearTimeout(this.timeout);
                }
                this.getServeTime(new Date(contest.endDate).getTime());
              }
            }
            return;
          }
        });
      } else {
        getCompetitionDetail(this.passParams.id).then((data) => {
          if (data.code == 1) {
            let contest = data.attribute.data;
            _this.contestStatus = contest.activityStatus;
            _this.competeDetail = contest;
            if (_this.contestStatus == '1') {
              _this.startContestStatus = true;
              _this.stopContestStatus = false;
              _this.currentStatus = 'preCompeManage';
              if (needServerTime) {
                if (this.timeout) {
                  clearTimeout(this.timeout);
                }
                this.getServeTime(new Date(contest.endDate).getTime());
              }
            } else if (_this.contestStatus == '0') {
              _this.startContestStatus = false;
              _this.stopContestStatus = true;
              _this.currentStatus = 'preCompeManage';
              if (needServerTime) {
                if (this.timeout) {
                  clearTimeout(this.timeout);
                }
                this.getServeTime(new Date(contest.startDate).getTime());
              }
            } else {
              _this.startContestStatus = true;
              _this.stopContestStatus = true;
              _this.currentStatus = 'endCompeManage';
              if (needServerTime) {
                if (this.timeout) {
                  clearTimeout(this.timeout);
                }
                this.getServeTime(new Date(contest.endDate).getTime());
              }
            }
            return;
          }
        });
      }
    },
    ...mapMutations('compet', ['setHasUser', 'setHasQues']),
    // 跳转大屏
    showVisualization() {
      let routeData = this.$router.resolve({
        path: '/knowledgeCompe',
        query: {
          name: this.passParams.name,
          id: this.passParams.id,
          status: this.passParams.status,
          sTime: this.passParams.sTime,
          eTime: this.passParams.eTime
        }
      });
      window.openTrain(routeData.href, '_blank');
    },
    showKnowLedgeCompetModel() {
      this.$refs.knowledgeModels.openModel(this.competeDetail, true);
    },
    validateStart() {
      Promise.all([this.queryAllQuestion(), this.getSenceUserList()]).then((data) => {
        this.setHasQues(data[0] > 0);
        this.setHasUser(data[1] > 0);
        this.$Message.info('校验完成');
      });
    }
  },
  mounted() {
    this.$store.commit('addBreadItem', { name: this.passParams.name });
    this.getContestStatus(true);
    Promise.all([this.queryAllQuestion(), this.getSenceUserList()]).then((data) => {
      this.setHasQues(data[0] > 0);
      this.setHasUser(data[1] > 0);
    });
  },
  beforeDestroy() {
    clearTimeout(this.timeout);
  }
};
</script>
<style scoped src="../../../view/drill_compete/detail.css">
</style>
